//
//  MYPublishEditCategoryVC.m
//  MuYing
//
//  Created by tbb on 2019/8/15.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "MYPublishEditCategoryVC.h"
#import "YQNavTitleView.h"
#import "YQSearchBaseBar.h"
#import "MYPublishEditCategoryModel.h"
@interface MYPublishEditCategoryVC ()<YQSearchBaseBarDelegate>
@property (nonatomic, strong) YQSearchBaseBar * searchBar;

@property (nonatomic, strong) NSMutableArray * categoryArr;
@property (nonatomic, copy) NSMutableArray * selectClassArr;

@end

@implementation MYPublishEditCategoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = true;
}

-(void)setupView {
    [super setupView];
    YQNavTitleView *navView = [YQNavTitleView new];
    navView.frame = CGRectMake(0, 0, kScreenWidth, 44);
    navView.intrinsicContentSize = CGSizeMake(kScreenWidth, 44);
    self.navigationItem.titleView = navView;
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = UIColor.whiteColor;
    [navView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 44));
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:0];
    [backBtn setImage:YQIMG(@"Publish_back_icon") forState:(UIControlStateNormal)];
    ws(self);
    [backBtn addTapAction:^(id  _Nonnull sender) {
        [weakself.navigationController popViewControllerAnimated:true];
    }];
    
    [bgView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    
    UIButton *determineBtn = [UIButton buttonWithType:0];
    determineBtn.titleLabel.font = [UIFont systemFontOfSize:15 weight:(UIFontWeightMedium)];
    [determineBtn setTitleColor:kAPPThemeColor forState:(UIControlStateNormal)];
    [determineBtn setTitle:kYQLS(@"确定") forState:(UIControlStateNormal)];
    
    [determineBtn addTarget:self action:@selector(determineAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [bgView addSubview:determineBtn];
    [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12);
        make.centerY.mas_equalTo(0);
        make.height.mas_equalTo(22);
    }];
    
    [bgView addSubview:self.searchBar];

    kYQREGISTERTABLEVIEWCNIBHeaderFooter(@"MYPublishEditCategoryHeader")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYPublishEditCategoryClassCell")
    [self getCategoryList];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
    
}

-(void)getCategoryList {
    
    
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_INVITATION_CATEGORY_LIST_MANAGER_URL parameters:nil success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {

            [self.categoryArr removeAllObjects];
            
            NSArray *arr = [NSArray modelArrayWithClass:MYPublishEditClassModel.class json:responseObject.data];

            NSMutableArray *parentModelArr = @[].mutableCopy;
            NSMutableArray *parentNameArr = @[].mutableCopy;

            for (MYPublishEditClassModel * classModel in arr) {
                MYPublishEditCategoryModel *categoryModel = [MYPublishEditCategoryModel new];
                if (parentModelArr.count > 0) {
                    if (![parentNameArr containsObject:classModel.parentName]) {
                        [parentNameArr addObject:classModel.parentName];
                        
                        categoryModel.parentName = classModel.parentName;
                        categoryModel.type = classModel.type;
                        [parentModelArr addObject:categoryModel];
                    }
                }else{
                    [parentNameArr addObject:classModel.parentName];
                    
                    categoryModel.parentName = classModel.parentName;
                    categoryModel.type = classModel.type;
                    [parentModelArr addObject:categoryModel];
                }
            }
            
            for (MYPublishEditCategoryModel *categoryModel in parentModelArr) {
                NSMutableArray *classModelArr = @[].mutableCopy;
                for (MYPublishEditClassModel * classModel in arr) {
                    if ([categoryModel.parentName isEqualToString:classModel.parentName]) {
                        [classModelArr addObject:classModel];
                    }
                }
                categoryModel.classArr = classModelArr.copy;
            }
            
            [self.categoryArr addObjectsFromArray:parentModelArr];
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
    }];
}

-(void)determineAction:(UIButton *)sender {
    if (self.selectClassArr.count > 0) {
        if (self.selectClassBlock) {
            self.selectClassBlock(self.selectClassArr.copy);
        }
        [self.navigationController popViewControllerAnimated:true];
    }else{
        [QMUITips showError:kYQLS(@"请选择分类") inView:self.view hideAfterDelay:1];
    }
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.categoryArr.count;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MYPublishEditCategoryModel *categoryModel = nil;
    if (section < self.categoryArr.count) {
        categoryModel = self.categoryArr[section];
    }
    
    if (categoryModel.isShow) {
        return categoryModel.classArr.count;
    }
    return 0;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    MYPublishEditCategoryModel *categoryModel = nil;
    if (indexPath.section < self.categoryArr.count) {
        categoryModel = self.categoryArr[indexPath.section];
    }
    
    MYPublishEditCategoryClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYPublishEditCategoryClassCell"];
    
    MYPublishEditClassModel *classModel = nil;
    if (indexPath.row < categoryModel.classArr.count) {
        classModel = categoryModel.classArr[indexPath.row];
    }
    cell.titleLb.text = classModel.name;
    cell.selectBtn.selected = classModel.isSelected;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    MYPublishEditCategoryClassCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    cell.selectBtn.selected = YES;
//    self.classStr = cell.titleLb.text;
    MYPublishEditCategoryModel *categoryModel = nil;
    if (indexPath.section < self.categoryArr.count) {
        categoryModel = self.categoryArr[indexPath.section];
    }
    MYPublishEditClassModel *classModel = nil;
    if (indexPath.row < categoryModel.classArr.count) {
        classModel = categoryModel.classArr[indexPath.row];
    }
    
    
    classModel.selected = !classModel.isSelected;
    
    if (self.selectClassArr.count == 0) {
        [self.selectClassArr addObject:classModel];
    }else{
        //大类是否已经改变，不能同时选择两个大类
        MYPublishEditClassModel *tempClassModel = self.selectClassArr.firstObject;
        if ([tempClassModel.parentName isEqualToString:categoryModel.parentName]) {
            if (classModel.selected) {
                [self.selectClassArr addObject:classModel];
            }else{
                [self.selectClassArr removeObject:classModel];
            }
        }else{
            for (MYPublishEditClassModel *selectClassModel in self.selectClassArr) {
                selectClassModel.selected = NO;
            }
            [self.selectClassArr removeAllObjects];
            [self.selectClassArr addObject:classModel];
        }
    }
    
    [self.listTableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MYPublishEditCategoryHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYPublishEditCategoryHeader"];
    
    MYPublishEditCategoryModel *categoryModel = nil;
    if (section < self.categoryArr.count) {
        categoryModel = self.categoryArr[section];
    }
    header.titleLb.text = categoryModel.parentName;
    
    header.contentView.tag = 11100 + section;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showClassAction:)];
    [header.contentView addGestureRecognizer:tap];
    return header;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 58;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
-(void)showClassAction:(UITapGestureRecognizer *)sender {
    NSInteger section = sender.view.tag - 11100;
    
    MYPublishEditCategoryModel *categoryModel = nil;
    if (section < self.categoryArr.count) {
        categoryModel = self.categoryArr[section];
    }
    
    for (MYPublishEditCategoryModel *tempCategoryModel in self.categoryArr) {
        if ([categoryModel.parentName isEqualToString:tempCategoryModel.parentName]) {
            tempCategoryModel.isShow = !tempCategoryModel.isShow;
        }else{
            tempCategoryModel.isShow = NO;
        }
    }
    
    [self.listTableView reloadData];
    
}
#pragma makr -- lazy
-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH - 94, 28)];
        _searchBar.top = 8;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"选择你要的分类");
        _searchBar.hidden = YES;
    }
    return _searchBar;
}

-(NSMutableArray *)categoryArr {
    if (!_categoryArr) {
        _categoryArr = [NSMutableArray array];
    }
    return _categoryArr;
}

-(NSMutableArray *)selectClassArr {
    if (!_selectClassArr) {
        _selectClassArr = [NSMutableArray array];
    }
    return _selectClassArr;
}

#pragma makr -- lazy end

#pragma makr -- YQSearchBaseBarDelegate
- (void)yq_searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
}
-(void)yq_textFieldShouldClear:(UITextField *)textField {
    
}
-(void)yq_shouldChangeText:(NSString *)text {
    
}
#pragma makr -- YQSearchBaseBarDelegate end
@end
